package com.zzl.admin.utils;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * description: Spring上下文提供者（动态获取bean实例）
 * @author 朱正磊
 * @date 2022-02-07 15:28:12
 */
@Component
public class ApplicationContextProvider implements ApplicationContextAware {

    /**
     * Spring上下文对象实例
     */
    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        ApplicationContextProvider.applicationContext = applicationContext;
    }

    /**
     * description: 获取Spring上下文对象实例
     * @author 朱正磊
     * @date 2022-02-07 15:34:13
     * @return 返回Spring上下文
     */
    public static ApplicationContext getApplicationContext() {
        return ApplicationContextProvider.applicationContext;
    }

    /**
     * description: 获取bean
     * @author 朱正磊
     * @date 2022-02-07 15:39:32
     * @param name bean的name
     * @return 返回bean对象
     */
    public static Object getBean(String name) {
        return getApplicationContext().getBean(name);
    }

    /**
     * description: 获取bean
     * @author 朱正磊
     * @date 2022-02-07 15:39:38
     * @param clazz 类的字节码
     * @param <T> 泛型
     * @return 返回bean对象
     */
    public static <T> T getBean(Class<T> clazz) {
        return getApplicationContext().getBean(clazz);
    }

    /**
     * description: 获取bean
     * @author 朱正磊
     * @date 2022-02-07 15:39:45
     * @param name bean的name
     * @param clazz 类的字节码
     * @param <T> 泛型
     * @return 返回bean对象
     */
    public static <T> T getBean(String name, Class<T> clazz) {
        return getApplicationContext().getBean(name, clazz);
    }

}
